package edu.unh.sustain;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.xml.sax.SAXException;

import android.util.Log;

public class XMLfunctions {
	
	// ***************************** buildingXMLfromWeb ***********************
	public static Document buildingXMLfromWeb()
	{
		Document doc = null;
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		URL url;
		
		// address of the building list XML
		String address = "http://energy.sr.unh.edu/Buildings/XMLList.pm";
		
		try {
			DocumentBuilder db = dbf.newDocumentBuilder();
			url = new URL(address);
			doc = db.parse(url.openStream());
		} catch (ParserConfigurationException e) {
			Log.w("EXCEPTION", "ParserConfigurationException");
			return null;
		} catch (SAXException e) {
			Log.w("EXCEPTION", "SAXException");
			return null;
		} catch (MalformedURLException mue) {
			Log.w("EXCEPTION", "MALFORMED URL");
		} catch (IOException e) {
			Log.w("EXCEPTION", "IOException 2");
			Log.w("EXCEPTION", e.toString());
		}
		
		return doc;
	}
	
	// ***************************** chartXMLfromWeb **************************
		public static Document chartXMLfromWeb(String id, String period, int y, int m, int d)
		{
			Document doc = null;
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			URL url;
			StringBuilder sb;
			
			sb = new StringBuilder("http://energy.sr.unh.edu/Readings/Building.pm?&BUILDING_ID=");
			sb.append(id);
			sb.append("&START_DATE=");
			sb.append(Integer.toString(y));
			sb.append("/");
			sb.append(Integer.toString(m));
			sb.append("/");
			sb.append(Integer.toString(d));
			sb.append("/");
			sb.append("&PERIOD=");
			sb.append(period.toLowerCase());
			
			Log.w("URL IS", sb.toString());
			
			try {
				DocumentBuilder db = dbf.newDocumentBuilder();
				url = new URL(sb.toString());
				doc = db.parse(url.openStream());
			} catch (ParserConfigurationException e) {
				Log.w("EXCEPTION", "ParserConfigurationException");
				return null;
			} catch (SAXException e) {
				Log.w("EXCEPTION", "SAXException");
				return null;
			} catch (MalformedURLException mue) {
				Log.w("EXCEPTION", "MALFORMED URL");
			} catch (IOException e) {
				Log.w("EXCEPTION", "IOException 2");
				Log.w("EXCEPTION", e.toString());
			}
			
			return doc;
		}
}
